<template>
  <div class="seller-home">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <h2>卖家管理中心</h2>
      </div>
      <div class="header-right">
        <el-dropdown @command="handleCommand">
          <el-button>
            <el-icon><User /></el-icon>
            {{ userInfo.username }}
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="personalInfo">修改个人信息</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-container class="main-container">
      <!-- 左侧菜单 -->
      <el-aside width="200px" class="aside">
        <el-menu
          :default-active="activeMenu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="orders">
            <el-icon><Document /></el-icon>
            <span>订单管理</span>
          </el-menu-item>
          <el-menu-item index="products">
            <el-icon><Goods /></el-icon>
            <span>商品管理</span>
          </el-menu-item>
          <el-menu-item index="categories">
            <el-icon><Folder /></el-icon>
            <span>分类管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧内容 -->
      <el-main class="main">
        <!-- 商品管理 -->
        <div v-if="activeMenu === 'products'" class="content-section">
          <div class="section-header">
            <h3>商品管理</h3>
            <div class="header-actions">
              <el-input
                v-model="productSearchKeyword"
                placeholder="搜索商品名称"
                style="width: 200px; margin-right: 10px"
                @keyup.enter="handleProductSearch"
              >
                <template #append>
                  <el-button @click="handleProductSearch">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </template>
              </el-input>
              <el-button type="primary" @click="showAddProductDialog = true">
                <el-icon><Plus /></el-icon>
                添加商品
              </el-button>
            </div>
          </div>

          <!-- 调试信息 -->
          <div v-if="debugInfo" style="background: #f0f9ff; padding: 10px; margin-bottom: 20px; border-radius: 4px;">
            <h4>调试信息：</h4>
            <p>商品数量: {{ products.length }}</p>
            <p>用户信息: {{ JSON.stringify(userInfo) }}</p>
            <p>分类数量: {{ categories.length }}</p>
            <p>商品数据: {{ JSON.stringify(products) }}</p>
          </div>

          <el-table 
            :data="products" 
            style="width: 100%"
            @selection-change="handleProductSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="price" label="价格" width="100">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100" />
            <el-table-column prop="sales" label="销量" width="100" />
            <el-table-column prop="categoryName" label="分类名称" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getProductStatusType(scope.row.status)">
                  {{ getProductStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="图片" width="120">
              <template #default="scope">
                <el-image 
                  :src="getImageUrl(scope.row.images)" 
                  style="width:60px;height:60px; object-fit:cover;" 
                  v-if="scope.row.images"
                  :preview-src-list="[getImageUrl(scope.row.images)]"
                  fit="cover"
                />
                <span v-else style="color: #999;">无图片</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <el-button size="small" @click="editProduct(scope.row)">
                  编辑
                </el-button>
                <el-button 
                  size="small" 
                  type="warning" 
                  @click="showStockDialog(scope.row)"
                >
                  库存
                </el-button>
                <el-button 
                  size="small" 
                  type="info" 
                  @click="showPriceDialog(scope.row)"
                >
                  价格
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteProduct(scope.row.id)"
                >
                  删除
                </el-button>
                <el-button size="small" type="primary" @click="showImageDialog(scope.row)">
                  修改图片
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 批量操作 -->
          <div v-if="selectedProducts.length > 0" class="batch-actions">
            <el-button 
              type="danger" 
              @click="batchDeleteProducts"
            >
              批量删除 ({{ selectedProducts.length }})
            </el-button>
          </div>
        </div>

        <!-- 订单管理 -->
        <div v-if="activeMenu === 'orders'" class="content-section">
          <div class="section-header">
            <h3>订单管理</h3>
            <div class="header-actions">
              <el-select 
                v-model="orderStatusFilter" 
                placeholder="订单状态" 
                style="width: 120px; margin-right: 10px"
                @change="handleOrderStatusFilter"
              >
                <el-option label="全部" value="" />
                <el-option label="待付款" :value="0" />
                <el-option label="待发货" :value="1" />
                <el-option label="已发货" :value="2" />
                <el-option label="已完成" :value="3" />
                <el-option label="已取消" :value="4" />
              </el-select>
              <el-input
                v-model="orderSearchKeyword"
                placeholder="搜索订单号或买家"
                style="width: 200px; margin-right: 10px"
                @keyup.enter="handleOrderSearch"
              >
                <template #append>
                  <el-button @click="handleOrderSearch">
                    <el-icon><Search /></el-icon>
                  </el-button>
                </template>
              </el-input>
            </div>
          </div>

          <el-table :data="orders" style="width: 100%">
            <el-table-column prop="id" label="订单ID" width="100" />
            <el-table-column prop="orderNo" label="订单号" width="150" />
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="buyerName" label="买家" width="120" />
            <el-table-column prop="quantity" label="数量" width="80" />
            <el-table-column prop="totalAmount" label="总金额" width="120">
              <template #default="scope">
                ¥{{ scope.row.totalAmount }}
              </template>
            </el-table-column>
            <el-table-column prop="orderStatus" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.orderStatus)">
                  {{ getStatusText(scope.row.orderStatus) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button
                  v-if="scope.row.orderStatus === 1"
                  size="small"
                  type="success"
                  @click="shipOrderAction(scope.row.id)"
                >
                  发货
                </el-button>
                <el-button
                  v-if="scope.row.orderStatus === 2"
                  size="small"
                  type="primary"
                  @click="handleUpdateOrderStatus(scope.row.id, 3)"
                >
                  确认收货
                </el-button>
                <el-button
                  size="small"
                  @click="showOrderDetail(scope.row)"
                >
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分类管理 -->
        <div v-if="activeMenu === 'categories'" class="content-section">
          <div class="section-header">
            <h3>分类管理</h3>
            <el-button type="primary" @click="showAddCategoryDialog = true">
              <el-icon><Plus /></el-icon>
              添加分类
            </el-button>
          </div>
          <el-table :data="categories" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="分类名称" />
            <el-table-column prop="level" label="层级" width="100" />
            <el-table-column prop="parentId" label="父分类ID" width="120" />
          </el-table>
        </div>
      </el-main>
    </el-container>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      v-model="showAddProductDialog"
      :title="editingProduct ? '编辑商品' : '添加商品'"
      width="600px"
    >
      <el-form
        ref="productFormRef"
        :model="productForm"
        :rules="productRules"
        label-width="100px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name" />
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="productForm.price"
            :precision="2"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number
            v-model="productForm.stock"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryId">
          <el-select v-model="productForm.categoryId" style="width: 100%">
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            action="http://localhost:8080/Products/upload/image"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
            accept="image/*"
            :on-success="handleImageUploadSuccess"
            with-credentials
          >
            <el-button type="primary">选择图片</el-button>
          </el-upload>
          <div v-if="productForm.images" style="margin-top:10px;">
            <img :src="getImageUrl(productForm.images)" style="max-width:100px; max-height:100px; object-fit:cover;" />
            <el-button size="small" type="danger" style="margin-left:10px;" @click="removeProductImage">
              删除图片
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddProductDialog = false">取消</el-button>
        <el-button type="primary" @click="saveProduct">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改个人信息对话框 -->
    <el-dialog v-model="showPersonalInfoDialog" title="修改个人信息" width="400px">
      <el-form :model="personalInfoForm" :rules="personalInfoRules" ref="personalInfoFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="personalInfoForm.username" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="personalInfoForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="personalInfoForm.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="personalInfoForm.address" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPersonalInfoDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPersonalInfo">保存</el-button>
      </template>
    </el-dialog>

    <!-- 添加分类弹窗 -->
    <el-dialog v-model="showAddCategoryDialog" title="添加分类" width="400px">
      <el-form :model="categoryForm" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="categoryForm.name" />
        </el-form-item>
        <el-form-item label="层级">
          <el-input-number v-model="categoryForm.level" :min="1" :max="3" />
        </el-form-item>
        <el-form-item label="父分类ID">
          <el-input v-model="categoryForm.parentId" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddCategoryDialog = false">取消</el-button>
        <el-button type="primary" @click="addCategory">添加</el-button>
      </template>
    </el-dialog>

    <!-- 上传商品图片对话框 -->
    <el-dialog v-model="showImageDialogVisible" title="修改商品图片" width="500px">
      <div style="text-align: center;">
        <el-upload
          :action="null"
          :http-request="handleImageUpload"
          :show-file-list="false"
          :auto-upload="false"
          :before-upload="beforeImageUploadDialog"
          accept="image/*"
        >
          <el-button type="primary">
            <el-icon><Upload /></el-icon>
            选择新图片
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB
            </div>
          </template>
        </el-upload>
        
        <div v-if="imagePreview" style="margin-top: 20px;">
          <h4>图片预览：</h4>
          <img :src="imagePreview" style="max-width: 100%; max-height: 300px; object-fit: contain;" />
        </div>
        
        <div v-if="currentProduct && currentProduct.images" style="margin-top: 20px;">
          <h4>当前图片：</h4>
          <img :src="getImageUrl(currentProduct.images)" style="max-width: 100%; max-height: 200px; object-fit: contain;" />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showImageDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitImageUpload" :disabled="!imageFile">
          确认上传
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../api/request.js'
import {
  getSellerProducts,
  addSellerProduct,
  updateSellerProduct,
  deleteSellerProduct,
  searchSellerProducts,
  updateProductStock,
  updateProductPrice,
  uploadSellerProductImage,
  uploadImage,
  getSellerOrders,
  getSellerOrderById,
  updateSellerOrderStatus,
  shipOrder,
  confirmOrder,
  getSellerStats,
  getProductSalesStats,
  getOrderStats
} from '../api/seller.js'
import {
  getOrdersBySellerId,
  getOrdersByStatusS,
  getOrderById,
  updateOrderStatus as updateOrderStatusApi
} from '../api/order.js'
import { getAllCategories, addSellerCategory } from '../api/category.js'
import { getUserInfo, updateUserInfo } from '../api/user.js'
import { 
  User, 
  ArrowDown, 
  Goods, 
  Document, 
  Folder, 
  Search, 
  Plus,
  Upload
} from '@element-plus/icons-vue'

const router = useRouter()

// 响应式数据
const activeMenu = ref('products')
const products = ref([])
const orders = ref([])
const categories = ref([])
const showAddProductDialog = ref(false)
const editingProduct = ref(null)
const userInfo = ref({ username: '卖家' })
const showPersonalInfoDialog = ref(false)
const personalInfoForm = reactive({ username: '', phone: '', email: '', address: '' })
const personalInfoFormRef = ref()
const productFormRef = ref()
const personalInfoRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确手机号', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确邮箱', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
}

const productForm = reactive({
  name: '',
  price: 0,
  stock: 0,
  categoryId: '',
  description: '',
  images: '',
  imageFile: null
})

const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入商品库存', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ]
}

const productSearchKeyword = ref('')
const selectedProducts = ref([])
const orderStatusFilter = ref('')
const orderSearchKeyword = ref('')
const showAddCategoryDialog = ref(false)
const categoryForm = reactive({ name: '', parentId: 0, level: 1 })
const showImageDialogVisible = ref(false)
const currentProduct = ref(null)
const imageFile = ref(null)
const imagePreview = ref('')
const debugInfo = ref(false)

// 图片上传配置
const uploadUrl = 'http://localhost:8080/Products/upload/image'
const uploadHeaders = {
  'Content-Type': 'multipart/form-data'
}

// 方法
const loadProducts = async () => {
  try {
    console.log('开始加载商品...')
    const res = await getSellerProducts()
    console.log('商品加载响应:', res)
    
    // 检查多种可能的状态码字段
    const statusCode = res.state || res.code || res.status || res.statusCode
    
    if (statusCode === 200) {
      products.value = res.data || []
      console.log('商品加载成功，商品数量:', products.value.length)
    } else if (statusCode === 401) {
      console.warn('用户未登录，尝试获取所有商品作为备用方案')
      // 如果用户未登录，尝试获取所有商品作为备用方案
      try {
        const allProductsRes = await request({
          url: '/Products',
          method: 'get'
        })
        if (allProductsRes.code === 200) {
          products.value = allProductsRes.data || []
          console.log('备用方案成功，获取到所有商品，数量:', products.value.length)
        } else {
          ElMessage.error('获取商品失败: ' + (res.message || '未知错误'))
        }
      } catch (backupError) {
        console.error('备用方案也失败:', backupError)
        ElMessage.error('获取商品失败: ' + (res.message || '未知错误'))
      }
    } else {
      console.error('商品加载失败，状态码:', statusCode, '消息:', res.message)
      ElMessage.error(res.message || '获取商品失败')
    }
  } catch (error) {
    console.error('获取商品失败:', error)
    console.error('错误详情:', error.response?.data)
    ElMessage.error('获取商品失败: ' + (error.message || '未知错误'))
  }
}

const loadOrders = async () => {
  const res = await getUserInfo()
  if (res && res.data && res.data.id) {
    userInfo.value = res.data
    const orderRes = await getOrdersBySellerId(userInfo.value.id)
    orders.value = orderRes.data || []
  }
}

const loadCategories = async () => {
  try {
    const res = await getAllCategories()
    console.log('分类数据', res)
    // 检查响应状态
    if (res.state === 200 || res.code === 200) {
      categories.value = res.data || []
    } else {
      ElMessage.error(res.message || '加载分类失败')
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    ElMessage.error('加载分类失败')
  }
}

const loadUserInfo = async () => {
  try {
    const res = await getUserInfo()
    // 检查响应状态
    if (res.state === 200 || res.code === 200) {
      Object.assign(personalInfoForm, {
        username: res.data.username || '',
        phone: res.data.phone || '',
        email: res.data.email || '',
        address: res.data.address || ''
      })
      userInfo.value = res.data || { username: '卖家' }
    } else {
      ElMessage.error(res.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

const handleMenuSelect = (index) => {
  activeMenu.value = index
  if (index === 'products') {
    loadProducts()
  } else if (index === 'orders') {
    loadOrders()
  } else if (index === 'categories') {
    loadCategories()
  }
}

const editProduct = (product) => {
  editingProduct.value = product
  Object.assign(productForm, {
    name: product.name,
    price: product.price,
    stock: product.stock,
    categoryId: product.categoryId,
    description: product.description,
    images: product.images
  })
  showAddProductDialog.value = true
}

const saveProduct = async () => {
  try {
    await productFormRef.value.validate()
    
    const productData = {
      name: productForm.name,
      price: productForm.price,
      stock: productForm.stock,
      categoryId: productForm.categoryId,
      description: productForm.description,
      images: productForm.images
    }
    
    let res
    if (editingProduct.value) {
      // 更新商品
      res = await updateSellerProduct(editingProduct.value.id, productData)
    } else {
      // 添加商品
      res = await addSellerProduct(productData)
    }
    
    if (res.code === 200) {
      ElMessage.success(editingProduct.value ? '更新成功' : '添加成功')
      showAddProductDialog.value = false
      resetProductForm()
      await loadProducts()
    } else {
      ElMessage.error(res.message || (editingProduct.value ? '更新失败' : '添加失败'))
    }
  } catch (error) {
    console.error('保存商品失败:', error)
    ElMessage.error('保存失败')
  }
}

const deleteProduct = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该商品？', '提示')
    const res = await deleteSellerProduct(id)
    
    // 检查响应状态
    if (res.code === 200) {
      ElMessage.success('删除成功')
      await loadProducts()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleUpdateOrderStatus = async (orderId, status) => {
  try {
    let res
    if (status === 2) {
      // 发货
      res = await shipOrder(orderId)
    } else if (status === 3) {
      // 确认收货
      res = await confirmOrder(orderId)
    } else {
      // 其他状态更新
      res = await updateOrderStatusApi(orderId, status)
    }
    
    // 检查响应状态
    if (res && (res.state === 200 || res.code === 200)) {
      if (status === 2) {
        ElMessage.success('发货成功')
      } else if (status === 3) {
        ElMessage.success('确认收货成功')
      } else {
        ElMessage.success('状态更新成功')
      }
      await loadOrders()
    } else {
      ElMessage.error(res?.message || '更新失败')
    }
  } catch (error) {
    console.error('更新订单状态失败:', error)
    ElMessage.error('更新失败')
  }
}

const handleImageChange = (file) => {
  productForm.images = file.raw
}

const resetProductForm = () => {
  editingProduct.value = null
  Object.assign(productForm, {
    name: '',
    price: 0,
    stock: 0,
    categoryId: '',
    description: '',
    images: ''
  })
}

const submitPersonalInfo = () => {
  personalInfoFormRef.value.validate(async valid => {
    if (!valid) return
    try {
      // 数据验证
      const submitData = {
        username: personalInfoForm.username?.trim() || '',
        phone: personalInfoForm.phone?.trim() || '',
        email: personalInfoForm.email?.trim() || '',
        address: personalInfoForm.address?.trim() || ''
      }
      
      // 验证必填字段
      if (!submitData.username) {
        ElMessage.error('用户名不能为空')
        return
      }
      
      await updateUserInfo(submitData)
      ElMessage.success('修改成功')
      showPersonalInfoDialog.value = false
      loadUserInfo()
    } catch (e) {
      ElMessage.error('修改失败')
    }
  })
}

const handleCommand = (command) => {
  switch (command) {
    case 'personalInfo':
      showPersonalInfoDialog.value = true
      loadUserInfo()
      break
    case 'logout':
      router.push('/login')
      break
  }
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'info',    // 待付款
    1: 'warning', // 待发货
    2: 'primary', // 已发货
    3: 'success', // 已完成
    4: 'danger'   // 已取消
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return textMap[status] || '未知'
}

const handleProductSearch = async () => {
  if (!productSearchKeyword.value.trim()) {
    await loadProducts()
    return
  }
  
  try {
    const res = await searchSellerProducts(productSearchKeyword.value)
    if (res.code === 200) {
      products.value = res.data || []
    } else {
      ElMessage.error(res.message || '搜索失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  }
}

const handleProductSelectionChange = (selection) => {
  selectedProducts.value = selection
}

const batchDeleteProducts = async () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要删除的商品')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确认删除选中的 ${selectedProducts.value.length} 个商品？`, 
      '批量删除确认'
    )
    
    // 批量删除
    const deletePromises = selectedProducts.value.map(product => 
      deleteSellerProduct(product.id)
    )
    await Promise.all(deletePromises)
    
    ElMessage.success('批量删除成功')
    selectedProducts.value = []
    await loadProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const showStockDialog = (product) => {
  ElMessageBox.prompt(
    `请输入 ${product.name} 的新库存数量`,
    '修改库存',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: product.stock,
      inputType: 'number',
      inputValidator: (value) => {
        if (value < 0) {
          return '库存不能为负数'
        }
        return true
      }
    }
  ).then(async ({ value }) => {
    try {
      const res = await updateProductStock(product.id, parseInt(value))
      if (res.code === 200) {
        ElMessage.success('库存更新成功')
        await loadProducts()
      } else {
        ElMessage.error(res.message || '更新库存失败')
      }
    } catch (error) {
      console.error('更新库存失败:', error)
      ElMessage.error('更新库存失败')
    }
  }).catch(() => {
    // 用户取消
  })
}

const showPriceDialog = (product) => {
  ElMessageBox.prompt(
    `请输入 ${product.name} 的新价格`,
    '修改价格',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: product.price,
      inputType: 'number',
      inputValidator: (value) => {
        if (value <= 0) {
          return '价格必须大于0'
        }
        return true
      }
    }
  ).then(async ({ value }) => {
    try {
      const res = await updateProductPrice(product.id, parseFloat(value))
      if (res.code === 200) {
        ElMessage.success('价格更新成功')
        await loadProducts()
      } else {
        ElMessage.error(res.message || '更新价格失败')
      }
    } catch (error) {
      console.error('更新价格失败:', error)
      ElMessage.error('更新价格失败')
    }
  }).catch(() => {
    // 用户取消
  })
}

const getProductStatusType = (status) => {
  const typeMap = {
    0: 'info',    // 下架
    1: 'success', // 上架
    2: 'warning', // 审核中
    3: 'danger'   // 已删除
  }
  return typeMap[status] || 'info'
}

const getProductStatusText = (status) => {
  const textMap = {
    0: '下架',
    1: '上架',
    2: '审核中',
    3: '已删除'
  }
  return textMap[status] || '未知'
}

const handleOrderStatusFilter = async () => {
  try {
    const params = {}
    if (orderStatusFilter.value !== '') {
      params.status = orderStatusFilter.value
    }
    const res = await getOrdersByStatusS(userInfo.value.id, params.status)
    if (res && (res.state === 200 || res.code === 200)) {
      orders.value = res.data || []
    } else {
      ElMessage.error(res?.message || '筛选失败')
    }
  } catch (error) {
    console.error('筛选订单失败:', error)
    ElMessage.error('筛选失败')
  }
}

const handleOrderSearch = async () => {
  if (!orderSearchKeyword.value.trim()) {
    await loadOrders()
    return
  }
  
  try {
    const params = { keyword: orderSearchKeyword.value }
    const res = await getOrdersByStatusS(userInfo.value.id, params.status)
    if (res && (res.state === 200 || res.code === 200)) {
      orders.value = res.data || []
    } else {
      ElMessage.error(res?.message || '搜索失败')
    }
  } catch (error) {
    console.error('搜索订单失败:', error)
    ElMessage.error('搜索失败')
  }
}

const showOrderDetail = (order) => {
  ElMessageBox.alert(
    `
    <div style="text-align: left;">
      <p><strong>订单号：</strong>${order.orderNo || order.id}</p>
      <p><strong>商品名称：</strong>${order.productName}</p>
      <p><strong>买家：</strong>${order.buyerName}</p>
      <p><strong>数量：</strong>${order.quantity}</p>
      <p><strong>总金额：</strong>¥${order.totalAmount}</p>
      <p><strong>状态：</strong>${getStatusText(order.orderStatus)}</p>
      <p><strong>创建时间：</strong>${order.createTime}</p>
      ${order.trackingNumber ? `<p><strong>物流单号：</strong>${order.trackingNumber}</p>` : ''}
      ${order.address ? `<p><strong>收货地址：</strong>${order.address}</p>` : ''}
    </div>
    `,
    '订单详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '确定'
    }
  )
}

// 测试接口方法
const testApi = async () => {
  console.log('开始测试接口...')
  
  try {
    // 测试用户信息接口
    console.log('测试用户信息接口...')
    const userRes = await getUserInfo()
    console.log('用户信息:', userRes)
    
    // 测试所有商品接口
    console.log('测试所有商品接口...')
    const allProductsRes = await request({
      url: '/Products',
      method: 'get'
    })
    console.log('所有商品:', allProductsRes)
    
    // 测试卖家商品接口
    console.log('测试卖家商品接口...')
    const sellerProductsRes = await getSellerProducts()
    console.log('卖家商品:', sellerProductsRes)
    
    // 测试分类接口
    console.log('测试分类接口...')
    const categoriesRes = await getAllCategories()
    console.log('分类:', categoriesRes)
    
    ElMessage.success('接口测试完成，请查看控制台')
  } catch (error) {
    console.error('接口测试失败:', error)
    ElMessage.error('接口测试失败: ' + error.message)
  }
}

// 根据分类ID获取分类名称
const getCategoryNameById = (categoryId) => {
  if (!categoryId) return '未分类'
  const category = categories.value.find(cat => cat.id === categoryId)
  return category ? category.name : '未分类'
}

const addCategory = async () => {
  try {
    await addSellerCategory(categoryForm)
    ElMessage.success('添加成功')
    showAddCategoryDialog.value = false
    await loadCategories()
    // 重置表单
    categoryForm.name = ''
    categoryForm.parentId = 0
    categoryForm.level = 1
  } catch (e) {
    ElMessage.error('添加失败')
  }
}

const showImageDialog = (product) => {
  currentProduct.value = product
  showImageDialogVisible.value = true
  imageFile.value = null
  imagePreview.value = product.images ? getImageUrl(product.images) : ''
}

const beforeImageUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true // 允许上传
}

const handleImageUpload = () => {} // 必须有，但不做事

// 处理添加商品时的图片上传
const handleAddProductImageUpload = async (options) => {
  const { file } = options
  
  try {
    // 先上传图片到服务器
    const formData = new FormData()
    formData.append('file', file)
    
    const res = await request({
      url: '/Products/upload/image',
      method: 'post',
      data: formData,
      headers: { 
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (res && (res.state === 200 || res.code === 200)) {
      productForm.images = res.data
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(res?.message || res?.msg || '图片上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败: ' + (error.response?.data?.message || error.message))
  }
}

const submitImageUpload = async () => {
  if (!imageFile.value) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  const formData = new FormData()
  formData.append('file', imageFile.value)
  
  try {
    const res = await uploadSellerProductImage(currentProduct.value.id, formData)
    if (res && (res.state === 200 || res.code === 200)) {
      ElMessage.success('图片上传成功')
      showImageDialogVisible.value = false
      await loadProducts() // 重新加载商品列表
    } else {
      ElMessage.error(res?.message || res?.msg || '上传失败')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败: ' + (error.response?.data?.message || error.message))
  }
}

const handleImageUploadSuccess = (response, file) => {
  // response.data 是后端返回的图片路径
  productForm.images = response.data;
  ElMessage.success('图片上传成功');
}

const removeProductImage = () => {
  productForm.images = ''
}

// 图片上传前的验证（用于修改图片对话框）
const beforeImageUploadDialog = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  
  imageFile.value = file
  const reader = new FileReader()
  reader.onload = e => {
    imagePreview.value = e.target.result
  }
  reader.readAsDataURL(file)
  return false // 阻止自动上传
}

// 获取图片完整URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  if (imagePath.startsWith('data:')) {
    return imagePath // 直接返回base64图片
  }
  if (imagePath.startsWith('http')) {
    return imagePath
  }
  // 确保路径以/开头
  const path = imagePath.startsWith('/') ? imagePath : '/' + imagePath
  return `http://localhost:8080${path}`
}

// 测试图片上传功能
const testImageUpload = async () => {
  try {
    // 创建一个测试文件
    const testFile = new File(['test'], 'test.jpg', { type: 'image/jpeg' })
    const formData = new FormData()
    formData.append('file', testFile)
    
    // 如果有商品，使用第一个商品进行测试
    if (products.value.length > 0) {
      const testProductId = products.value[0].id
      const res = await uploadSellerProductImage(testProductId, formData)
      console.log('图片上传测试结果:', res)
      ElMessage.success('图片上传功能正常')
    } else {
      ElMessage.warning('请先添加一个商品来测试图片上传功能')
    }
  } catch (error) {
    console.error('图片上传测试失败:', error)
    ElMessage.error('图片上传功能测试失败: ' + error.message)
  }
}

// 检查后端服务状态
const checkBackendStatus = async () => {
  try {
    const res = await request({
      url: '/Products',
      method: 'get'
    })
    console.log('后端服务状态检查:', res)
    return true
  } catch (error) {
    console.error('后端服务连接失败:', error)
    ElMessage.error('后端服务连接失败，请确保后端服务器在 http://localhost:8080 运行')
    return false
  }
}

const shipOrderAction = async (orderId) => {
  try {
    await ElMessageBox.confirm('确认发货？', '提示')
    const res = await shipOrder(orderId)
    if (res && (res.state === 200 || res.code === 200)) {
      ElMessage.success('发货成功')
      await loadOrders() // 重新加载订单列表
    } else {
      ElMessage.error(res?.message || '发货失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('发货失败')
    }
  }
}

// 调试商品功能
const debugProducts = async () => {
  debugInfo.value = !debugInfo.value
  if (debugInfo.value) {
    console.log('=== 调试信息 ===')
    console.log('商品数量:', products.value.length)
    console.log('用户信息:', userInfo.value)
    console.log('分类数量:', categories.value.length)
    console.log('商品数据:', products.value)
    
    // 尝试重新加载商品
    try {
      console.log('尝试重新加载商品...')
      await loadProducts()
      console.log('重新加载完成')
    } catch (error) {
      console.error('重新加载失败:', error)
    }
  }
}

// 生命周期
onMounted(async () => {
  console.log('SellerHome组件挂载，开始初始化...')
  
  // 检查后端服务状态
  const backendOk = await checkBackendStatus()
  if (!backendOk) {
    return
  }
  
  // 检查登录状态
  try {
    await loadUserInfo()
    console.log('用户信息加载成功:', userInfo.value)
  } catch (error) {
    console.error('用户信息加载失败:', error)
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  
  // 加载数据
  await loadProducts()
  await loadCategories()
})
</script>

<style scoped>
.seller-home {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #409eff;
}

.main-container {
  flex: 1;
  height: calc(100vh - 60px);
}

.aside {
  background: #fff;
  border-right: 1px solid #e4e7ed;
}

.main {
  padding: 20px;
  background: #f5f7fa;
}

.content-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  align-items: center;
}

.batch-actions {
  margin-top: 20px;
  text-align: right;
}
</style>  